import * as mars3d from "mars3d"
import { Cesium } from "mars3d"

export let map: any // mars3d.Map三维地图对象
export const eventTarget: mars3d.BaseClass = new mars3d.BaseClass()

/**
 * 初始化地图业务，生命周期钩子函数（必须）
 * 框架在地图初始化完成后自动调用该函数
 * @param {mars3d.Map} mapInstance 地图对象
 * @returns {void} 无
 */
export function onMounted(mapInstance: any): void {
  console.log("加载成功")
  map = mapInstance // 记录map
  console.log(map)
  load3DTiles("高新区", "//122.9.68.70:6789/zhengzhou/3dtiles/tileset.json", "GaoxinMesh")
  loadGeojson("高新区矢量数据", "//122.9.68.70:6789/zhengzhou/buildingFramework/aerial.json", "shiliang", "polygon")
  load3DTiles("电力塔", "//data.mars3d.cn/3dtiles/pnts-ganta/tileset.json", "dianlita")
  load3DTiles("点云", "//122.9.68.70:6789/zhengzhou/undergroundPipeGalleryLas/tileset.json", "dixiaguanlang")
  load3DTiles("单体化模型", "//122.9.68.70:6789/zhengzhou/single/tileset.json", "single")
  load3DTiles("北斗产业园", "//122.9.68.70:6789/zhengzhou/beidou/tileset.json", "BeidouMesh", { alt_offset: 20 })
  load3DTiles("室内建筑","//122.9.68.70:6789/School/tileset.json","School",{ alt_offset: 40 })//{"lat":31.84713,"lng":117.248081,"alt":46.6,"heading":223.8,"pitch":-12.3}
  // load3DTiles("黄河堤岸(点云)","//122.9.68.70:6789/zhengzhou/huanghelas/tileset.json","huanghelas")
  // loadGeojson("高新区矢量数据","//122.9.68.70:6789/zhengzhou/buildingFramework/aerial.json","shiliang")
  // loadundergroundpipe()
  let underground = new mars3d.thing.Underground({
    alpha: 0.4,
    enabled: false,
    id: "underground"
  })
  map.addThing(underground)
  loadpoint()
  loadGraphicPipe()
}

/**
 * 释放当前地图业务的生命周期函数
 * @returns {void} 无
 */
export function onUnmounted() {
  map = null
}

export function load3DTiles(name, url, id, position = {}) {
  const tilesLayer = new mars3d.layer.TilesetLayer({
    name: name,
    url: url,
    // center: { lat: 34.814603, lng: 113.551305, alt: 693.4, heading: 359.1, pitch: -43.5 },
    position: position,
    maximumScreenSpaceError: 1,
    dynamicScreenSpaceError: false,
    cullWithChildrenBounds: false,
    skipLevelOfDetail: false,
    preferLeaves: false,
    highlight: { type: "click", color: "#00ffff" },
    flyTo: false,
    id: id,
    show: false
  })
  map.addLayer(tilesLayer)
  tilesLayer.readyPromise.then(function (layer) {
    console.log("load完成", layer)
    eventTarget.fire("load", map)
  })
  // 加载的事件 只执行一次
  tilesLayer.on(mars3d.EventType.initialTilesLoaded, function (event) {
    console.log("触发initialTilesLoaded事件", event)
  })

  // 会执行多次，重新加载一次完成后都会回调
  // tilesLayer.on(mars3d.EventType.allTilesLoaded, function (event) {
  //   console.log("触发allTilesLoaded事件", event)
  // })
}

// 加载地下管网数据
export function loadundergroundpipe() {
  const tiles3dLayer = new mars3d.layer.TilesetLayer({
    name: "地下管网",
    id: "undergroundpipe",
    url: "//data.mars3d.cn/3dtiles/max-piping/tileset.json",
    position: { lng: 113.534, lat: 34.79602, alt: 50 },
    // position: { lng: 117.215457, lat: 31.843363, alt: -3.6 },
    rotation: { x: 0, y: 0, z: 336.7 },
    maximumScreenSpaceError: 2,
    highlight: { type: "click", outlineEffect: true, color: "#FFFF00" },
    show: false,
    popup: [
      { field: "id", name: "编码" },
      { field: "layer_name", name: "名称" },
      {
        type: "html",
        html: "<label>类型</label><label>矢量模型</label>"
      }
    ],
    center: { lat: 34.791129, lng: 113.534447, alt: 404.6, heading: 1, pitch: -34 }
  })
  map.addLayer(tiles3dLayer)

  // terrainClips(30)
}

export function loadGeojson(name, url, id, type) {
  const geojsonLayer = new mars3d.layer.GeoJsonLayer({
    name: name,
    url: url,
    id: id,
    show: false,
    symbol: {
      type: type,
      styleOptions: {
        color: "#0d3685",
        opacity: 1.0,
        outline: false
      },
      callback: function (attr) {
        const diffHeight = Number(attr.ELEV || 1)
        return { diffHeight }
      }
    },
    popup: "all"
  })
  map.addLayer(geojsonLayer)
}

export function loadGraphicPipe() {
  const graphicLayer = new mars3d.layer.GraphicLayer({
    id: "pipe",
    name: "管道",
    show: false,
    center: { lat: 34.791948, lng: 113.534755, alt: 396.3, heading: 359.1, pitch: -43.5 }
  })
  const graphic1 = new mars3d.graphic.PolylineVolumeEntity({
    positions: [
      [113.532027, 34.79525, 80],
      [113.53483, 34.795259, 80],
      [113.534808, 34.796275, 80]
    ],
    style: {
      shape: "pipeline",
      radius: 2,
      cornerType: Cesium.CornerType.BEVELED,
      materialType: mars3d.MaterialType.LineFlowColor,
      materialOptions: {
        color: "#3388ff",
        speed: 10,
        percent: 0.15,
        alpha: 0.2
      }
    },
    popup: "雨水管道"
    // attr: "all",
  })
  graphicLayer.addGraphic(graphic1)
  const graphic2 = new mars3d.graphic.PolylineVolumePrimitive({
    positions: [
      [113.534954, 34.794196, 80],
      [113.534944, 34.795199, 80],
      [113.536405, 34.795152, 80]
    ],
    style: {
      shape: "pipeline",
      radius: 2,
      // color: "#2bff50",
      cornerType: Cesium.CornerType.BEVELED,
      materialType: mars3d.MaterialType.LineFlowColor,
      materialOptions: {
        color: "#00ffff",
        speed: 10,
        percent: 0.15,
        alpha: 0.2
      }
    },
    popup: "污水管道"
    // attr: "all",
  })
  graphicLayer.addGraphic(graphic2)

  const graphic3 = new mars3d.graphic.RectanglePrimitive({
    positions: [
      [113.536404, 34.795133],
      [113.536453, 34.795169]
    ],
    style: {
      height: 85,
      image: "img/JingGai.png"
    }
  })
  graphicLayer.addGraphic(graphic3)
  map.addLayer(graphicLayer)
}

export function loadpoint() {
  let graphicLayer = new mars3d.layer.GraphicLayer({
    id: "beidouSys",
    allowDrillPick: false
  })
  map.addLayer(graphicLayer)
  let graphic = new mars3d.graphic.BillboardEntity({
    position: [113.537945, 34.796747, 93.6],
    style: {
      image: "img/marker/mark-blue.png",
      scale: 1,
      horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
      verticalOrigin: Cesium.VerticalOrigin.BOTTOM
    },
    show: true
  })
  graphicLayer.addGraphic(graphic) // 还可以另外一种写法: graphic.addTo(PointLayer)
  Popup(graphic)
}

function Popup(graphic) {
  graphic.bindPopup(
    function (event) {
      // if (event.graphics?.length > 1) {
      //     return `您单击了重叠图标，该区域有${event.graphics.length}个对象` // 如果存在坐标完全相同的图标点时
      // }
      // console.log(event)
      let attr = {
        经度: "113.537945",
        纬度: "34.796747",
        高程: "93.6",
        状态: "1",
        雨量: "0",
        振弦频率: "1540.830hz",
        温度: "6℃",
        湿度: "0%"
      }
      let attrKey = Object.keys(attr)
      let container: Element = document.createElement("div") // popup对应的DOM
      container.innerHTML = popupHtml
      // container.querySelector("#popupCloseButton").addEventListener("click", () => event.graphic.closePopup())
      let titlelogo = container.querySelector("#title-logo")
      let title = container.querySelector("#title")
      title.innerHTML = "传感器"
      let table = container.querySelector("#content") as HTMLElement
      for (let i = 0; i < attrKey.length; i++) {
        let row = document.createElement("div")
        row.style.cssText = "display: flex;align-items: center;font-size: 14px;margin-bottom: 10px;"
        let colid = "t" + (i + 1)
        row.setAttribute("id", colid)
        table.append(row)
        let col1 = document.createElement("div")
        col1.style.cssText = "width: 40%;color:#51d4ff;font-size:14px;text-align: left;"
        col1.setAttribute("id", colid + 1)
        col1.innerHTML = attrKey[i]
        row.append(col1)
        let col2 = document.createElement("div")
        col2.style.cssText = "width: 60%;font-size:14px;color: #FFFFFF;text-align: right;"
        col2.setAttribute("id", colid + 2)
        col2.append((document.createElement("p").innerHTML = attr[attrKey[i]]))
        row.append(col2)
      }
      // 处理好的html样式返回给popup
      return container
    },
    { offsetY: -35 }
  )
}

// 显示变化*****************
setInterval(function () {
  let num = document.querySelector("#t62")
  if (num) {
    num.innerHTML = (1540.83 + Math.random() * 0.1).toFixed(3).toString() + "hz"
  }
}, 10000)
let popupHtml = `<div id="popuproot" style="border-radius: 3px;padding: 15px;text-align: left;background-color: rgba(0,0,0,0.8);background-size: cover;width: 300px;">
  <div id="popup-box" style="width:auto;">
  <div id="popup-head" style="display: flex;align-items: center;">
    <img id="title-logo" src="" alt="" style="margin-right: 10px;">
    <div id="title" style="color: #ffffff;font-size: 16px;text-align: left;vertical-align: middle;"></div>
  </div>
    <div id="content" style="margin: 2px; width: 95%;">
    </div>
  </div>
</div>
`
